import 'package:capsule/widgets/dialog/dialog_template.dart';
import 'package:flutter/material.dart';

import '../../models/file_info.dart';
import '../../utils/file_utils.dart';
import '../form/form_input.dart';

class FileInfoEditorDialog extends StatefulWidget {
  final void Function(FileInfo? value)? onOk;
  final void Function()? onCancel;
  final FileInfo fileInfo;
  const FileInfoEditorDialog(
      {super.key, this.onOk, this.onCancel, required this.fileInfo});

  @override
  State<FileInfoEditorDialog> createState() => _FileInfoEditorDialogState();
}

class _FileInfoEditorDialogState extends State<FileInfoEditorDialog> {
  late final TextEditingController _titleController;
  late final TextEditingController _summaryController;
  final GlobalKey<FormState> _form = GlobalKey();
  @override
  void initState() {
    super.initState();

    _titleController = TextEditingController(text: widget.fileInfo.title);
    _summaryController = TextEditingController(text: widget.fileInfo.summary);
  }

  @override
  void dispose() {
    _titleController.dispose();
    _summaryController.dispose();
    super.dispose();
  }

  void _submit() {
    if (_form.currentState?.validate() == false) return;
    FileInfo fileInfo = widget.fileInfo;
    String title = _titleController.text;
    String summary = _summaryController.text;
    if (fileInfo.title != title || fileInfo.summary != summary) {
      widget.onOk?.call(fileInfo.copyWith(
          fullPath: replaceTitleInPath(fileInfo.fullPath, title),
          summary: summary));
    } else {
      widget.onOk?.call(null);
    }
  }

  @override
  Widget build(BuildContext context) {
    double dlgWidth = 560;
    return DialogTemplate(
      width: dlgWidth,
      height: 480,
      onCancel: widget.onCancel,
      onOk: () {
        _submit();
      },
      child: Form(
        key: _form,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text("名称"),
            const SizedBox(
              height: 5,
            ),
            FormInput(
              controller: _titleController,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return "名称不能为空";
                }
                return null;
              },
              onFieldSubmitted: (value) {
                _submit();
              },
            ),
            const SizedBox(
              height: 10,
            ),
            const Text("摘要"),
            const SizedBox(
              height: 5,
            ),
            FormInput(
              controller: _summaryController,
              onFieldSubmitted: (value) {
                _submit();
              },
              maxLines: 8,
            )
          ],
        ),
      ),
    );
  }
}
